import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export async function GET() {
  try {
    const strategies = await prisma.tradingStrategy.findMany({
      include: {
        token: true
      }
    });

    return NextResponse.json(strategies);
  } catch (error) {
    console.error('获取策略列表失败:', error);
    return NextResponse.json({ error: '获取策略列表失败' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      tokenId,
      isEnabled,
      rsiBuyThreshold,
      rsiSellThreshold,
      buyAmountSol,
      buyAmountBnb,
      buyAmountEth,
      firstDipPercent,
      secondDipPercent,
      maxPositions
    } = body;

    if (!tokenId) {
      return NextResponse.json({ error: '缺少tokenId参数' }, { status: 400 });
    }

    const strategy = await prisma.tradingStrategy.upsert({
      where: { tokenId },
      update: {
        isEnabled: isEnabled ?? false,
        rsiBuyThreshold: rsiBuyThreshold ?? 30,
        rsiSellThreshold: rsiSellThreshold ?? 60,
        buyAmountSol: buyAmountSol ?? 3.0,
        buyAmountBnb: buyAmountBnb ?? 0.5,
        buyAmountEth: buyAmountEth ?? 0.1,
        firstDipPercent: firstDipPercent ?? 20,
        secondDipPercent: secondDipPercent ?? 30,
        maxPositions: maxPositions ?? 3
      },
      create: {
        tokenId,
        isEnabled: isEnabled ?? false,
        rsiBuyThreshold: rsiBuyThreshold ?? 30,
        rsiSellThreshold: rsiSellThreshold ?? 60,
        buyAmountSol: buyAmountSol ?? 3.0,
        buyAmountBnb: buyAmountBnb ?? 0.5,
        buyAmountEth: buyAmountEth ?? 0.1,
        firstDipPercent: firstDipPercent ?? 20,
        secondDipPercent: secondDipPercent ?? 30,
        maxPositions: maxPositions ?? 3
      },
      include: {
        token: true
      }
    });

    return NextResponse.json(strategy);
  } catch (error) {
    console.error('创建/更新策略失败:', error);
    return NextResponse.json({ error: '创建/更新策略失败' }, { status: 500 });
  }
}
